import React, { useState, useEffect, useCallback } from 'react';
import { getDictionaryItemsByCode } from '@/pages/Dictionary/api';

export interface DictionaryItem {
  id: string;
  label: string;
  english?: string;
  value: string;
  orderNum: number;
  status: boolean;
}

interface UseDictionaryOptions {
  code: string;
  autoLoad?: boolean;
}

interface UseDictionaryReturn {
  items: DictionaryItem[];
  loading: boolean;
  error: string | null;
  refresh: () => Promise<void>;
  getLabel: (value: string) => string;
  getValue: (label: string) => string;
}

/**
 * 字典数据 Hook
 * 用于获取和使用字典数据
 * 
 * @example
 * const { items, loading, getLabel } = useDictionary({ code: 'user_status' });
 * const statusLabel = getLabel('active'); // 获取 'active' 对应的标签
 */
export function useDictionary(options: UseDictionaryOptions): UseDictionaryReturn {
  const { code, autoLoad = true } = options;
  const [items, setItems] = useState<DictionaryItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const loadDictionary = useCallback(async () => {
    if (!code) return;

    setLoading(true);
    setError(null);

    try {
      const response = await getDictionaryItemsByCode(code);
      if (response.data.success) {
        setItems(response.data.data || []);
      } else {
        setError(response.data.message || '获取字典数据失败');
      }
    } catch (err: any) {
      setError(err.message || '获取字典数据失败');
      console.error(`Failed to load dictionary: ${code}`, err);
    } finally {
      setLoading(false);
    }
  }, [code]);

  useEffect(() => {
    if (autoLoad) {
      loadDictionary();
    }
  }, [autoLoad, loadDictionary]);

  const getLabel = useCallback(
    (value: string): string => {
      const item = items.find((item) => item.value === value);
      return item?.label || value;
    },
    [items]
  );

  const getValue = useCallback(
    (label: string): string => {
      const item = items.find((item) => item.label === label);
      return item?.value || label;
    },
    [items]
  );

  return {
    items,
    loading,
    error,
    refresh: loadDictionary,
    getLabel,
    getValue,
  };
}

/**
 * 字典选项 Hook
 * 将字典数据转换为 Ant Design Select 组件的选项格式
 * 
 * @example
 * const statusOptions = useDictionaryOptions('user_status');
 * <Select options={statusOptions} />
 */
export function useDictionaryOptions(code: string) {
  const { items, loading } = useDictionary({ code });

  // 使用 useMemo 缓存选项，避免每次创建新数组
  const options = React.useMemo(() => {
    return items
      .filter(item => item.status) // 只返回启用的字典项
      .map((item) => ({
        label: item.label,
        value: item.value,
      }));
  }, [items]);

  return { options, loading };
}

